import Food from './Food'
import ScorePanel from './ScorePanel'
import Snake from './Snake'

class GameControl {
  snake: Snake;
  food: Food;
  scorePanel: ScorePanel;
  direction: string = 'Right';
  isLive: boolean = true
  constructor() {
    this.food = new Food()
    this.snake = new Snake()
    this.scorePanel = new ScorePanel(10,2)
    this.init()
  }
  init() {
    document.addEventListener('keydown', this.keydownHandler.bind(this))
    this.run()
  }
  // 键盘按下事件
  /**
   * 
   * @param event 
   *  ArrowUp UP
      ArrowDown Down
      ArrowLeft Left
      ArrowRight Right
   */
  keydownHandler(event: KeyboardEvent) {
    // console.log(event.key)
    this.direction = event.key
  }
  // 蛇移动
  run() {
    let X = this.snake.X
    let Y = this.snake.Y
    switch (this.direction) {
      case 'ArrowUp':
      case 'UP':
        Y -= 10
        break;
      case 'ArrowDown':
      case 'Down':
        Y += 10
        break;
      case 'ArrowLeft':
      case 'Left':
        X -= 10
        break;
      case 'ArrowRight':
      case 'Right':
        X += 10
        break;
      default:
        break;
    }
    // 判断是否吃到了食物
    this.checkEat(X,Y)

    // this.snake.X = X
    // this.snake.Y = Y

    try {
      this.snake.X = X
      this.snake.Y = Y
    } catch (error) {
      alert(error)
      this.isLive = false
    }
    // if (this.snake.isLive) {
    //   this.snake.X = X
    //   this.snake.Y = Y
    // } else {
    //   alert('失败了')
    //   this.isLive = false
    // }

    // 递归调用
    this.isLive && setTimeout(this.run.bind(this),300 - (this.scorePanel.level - 1) * 30)
  }
  // 判断是否吃到了食物
  checkEat(X:number,Y:number){
    if (X === this.food.X && Y === this.food.Y) {
      // 食物重新调整位置
      this.food.change()
      // 增加分数
      this.scorePanel.addScore()
      // 蛇增加子类元素
      this.snake.addBody()
    }
  }
}

export default GameControl